package com.changxianggu.cloud.crawler.core.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.xml.sax.SAXException;

import java.io.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportExcelUtil {

    private static final String TEMPLATE_PATH = "/template";

    /**
     * @param xmlPath     指向/classes/template/下的相对路径字符串
     * @param uploadExcel 上传文件输入流
     * @return
     */
    public static Map<String, Object> importExcel(String xmlPath, InputStream uploadExcel) {
        Map<String, Object> resultMap = new HashMap<>();
        // String absXmlPath = getFilePath(xmlPath);
        BufferedInputStream bisXML = null;
        BufferedInputStream bisExcel = null;
        List dataList = null;
        List<String> cellNameList = new ArrayList<>();
        String cellName = "";
        try {
            // 读入xml文件到缓冲流
            bisXML = new BufferedInputStream(ImportExcelUtil.class.getResourceAsStream(xmlPath));
            // 读入上传excel文件到缓冲流
            bisExcel = new BufferedInputStream(uploadExcel);
            dataList = new ArrayList<>();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("dataList", dataList);
            // 开始解析excel文件
            XLSReader mainReader = ReaderBuilder.buildFromXML(bisXML);
            // mainReader.getConvertUtilsBeanProvider().getConvertUtilsBean().deregister(java.util.Date.class);
            mainReader.getConvertUtilsBeanProvider().getConvertUtilsBean().register(new MyDateConverter(),
                    java.util.Date.class);
            // 放入承载数据Map中
            XLSReadStatus readStatus = mainReader.read(bisExcel, dataMap);
            resultMap.put("readStatus", readStatus);
            for (int i = 0; i < readStatus.getReadMessages().size(); i++) {
                XLSReadMessage message = (XLSReadMessage) readStatus.getReadMessages().get(i);
                if (StrUtil.isNotEmpty(message.getMessage())) {
                    int star = message.getMessage().indexOf("cell") + 5;
                    int end = message.getMessage().indexOf("on") - 1;
                    cellName = message.getMessage().substring(star, end);
                    cellNameList.add(MessageFormat.format("导入失败，{0}单元格填入数据有误，请按下载模版要求填写！", cellName));
                }
            }
            dataMap.put("cellNameList", cellNameList);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bisXML != null) {
                    bisXML.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bisExcel != null) {
                    bisExcel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        resultMap.put("dataList", dataList);
        return resultMap;
    }

    /**
     * 获取文件路径绝对路径
     *
     * @param filePath 指向/classes/template/下的相对路径字符串
     * @return
     * @see [类、类#方法、类#成员]
     */
    @Deprecated
    public static String getFilePath(String filePath) {
        // 获取classpath 路径
        String classPath = ExportExcelUtil.class.getResource("/").getPath();
        StringBuilder path = new StringBuilder();
        path.append(classPath).append(TEMPLATE_PATH).append(File.separator).append(filePath);
        return path.toString();
    }

}
